/**     
 * @{#} Client.java Create on 2011-7-22 下午12:56:26     
 *     
 * Copyright (c) 2011 by xiaofeng.zhouxf     
 */
package com.sefer.memcached.client;

import com.sefer.memcached.command.AddCommand;
import com.sefer.memcached.command.Command;
import com.sefer.memcached.command.GetCommand;
import com.sefer.memcached.configure.MCConfigure;
import com.sefer.memcached.connect.ConnectResources;
import com.sefer.memcached.connect.Server;
import com.sefer.memcached.constants.ErrorCode;
import com.sefer.memcached.exception.ClientException;
import com.sefer.memcached.lifecycle.LifeCycle;

/**
 * The entrance to call the memcached.
 * 
 * @author <a href="mailto:xiaofeng.zhouxf83@gmail.com">xiaofeng.zhouxf</a>
 * @version 1.0
 */
public class Client implements LifeCycle {
	private MCConfigure configure;
	private Server[] servers;
	private String lifeCycleStats = LifeCycle.STOP;

	void init(Server[] servers) {
		if (servers == null || servers.length == 0) {
			throw new ClientException(ErrorCode.E_400,
					"Create server params error");
		}
		this.servers = servers;
		ConnectResources resources = new ConnectResources(servers);
		configure = new MCConfigure(resources);
		this.setState(NEW);
	}

	@Override
	public boolean start() throws ClientException {
		if (LifeCycle.STOP == getState()) {
			init(servers);
		}

		if (this.lifeCycleStats == LifeCycle.NEW) {
			this.lifeCycleStats = LifeCycle.STATING;
			configure.setState(LifeCycle.STATING);
			configure.start();
			this.setState(STATED);
		}

		return true;
	}

	public boolean callServer(Command command) {
		if (getState() != STATED) {
			start();
		}
		try {
			configure.invokeCommand(command);
		} catch (ClientException e) {
			e.printStackTrace();
			return false;
		}

		return true;
	}

	@Override
	public boolean stop() throws ClientException {
		return configure.stop();
	}

	@Override
	public String getState() {
		return lifeCycleStats;
	}

	@Override
	public void setState(String state) {
		this.lifeCycleStats = state;
		if (configure != null)
			this.configure.setState(state);
	}

	public static void main(String[] args) {
		Client client = new Client();
		Server[] servers = new Server[1];
		servers[0] = new Server("10.16.42.195", 11211);
		client.init(servers);
		client.start();

		Command command = new AddCommand("xxxx", "teststest");
		boolean callServer = client.callServer(command);
		System.out.println(callServer);
		System.out.println("result: " + command.getResult());

		System.out.println("================================");

		Command getcommand = new GetCommand("xxxx");
		boolean getBooleanRet = client.callServer(command);
		System.out.println(getBooleanRet);
		System.out.println(getcommand.getResult());
	}
}
